package com.zsk.shop.config.interceptor;

import com.zsk.shop.config.MyHttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yuwenbo
 * @description:
 * @date 2019-05-26 17:11
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "CorsFilter")
public class CorsFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CorsFilter.class);

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest reqs = (HttpServletRequest) req;
//        String curOrigin = reqs.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Expose-Headers", "*");
        String a = reqs.getRequestURI();
        if (a.contains("/ivManagement") || a.contains("/druid") || a.contains("/serviceSocket") || a.contains("/pay/aliPayNotify.do")) {
            //如果发现是图片相关/druid相关/websocket相关
            chain.doFilter(req, res);
            return;
        }
        ServletRequest requestWrapper = null;
        if (req instanceof HttpServletRequest) {
            requestWrapper = new MyHttpServletRequestWrapper((HttpServletRequest) req);
        }
        if (requestWrapper == null) {
            chain.doFilter(req, res);
            return;
        } else {
            chain.doFilter(requestWrapper, res);
            return;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
        logger.info("========================Cors Filter Apply===============================");
    }

    @Override
    public void destroy() {
    }
}
